<?php

namespace application\admin\controllers;

use Yii;
use mz\controllers\DashController;
use mz\models\AdminModel;
use yii\helpers\Url;

class LoginController extends DashController
{

    public function actions()
    {
        return [
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'height' => 35,
                'maxLength' => 4,
                'minLength' => 4,
                'offset' => 10,
                'transparent' => true,
                'testLimit' => 0,
            ],
        ];
    }

    # 登录页面
    public function actionIndex()
    {
        return $this->renderPartial('index');
    }

    # 登录验证
    public function actionOauth()
    {
        if (!Yii::$app->admin->isGuest)return $this->ajaxReturn(['state' => 1, 'message' => '恭喜你，登录成功']);

        if (!Yii::$app->request->isPost)return $this->ajaxReturn(['state' => 1, 'message' => '请求方式错误']);

        $model = new AdminModel();

        $post = Yii::$app->request->post();
        $model->username = $post['username'];
        $model->password_hash = $post['password_hash'];
        $model->rememberMe = isset($post['rememberMe']) ? (bool)$post['rememberMe'] : 0;
        if ($model->login()) {
            $this->ajaxReturn([
                'state' => '0',
                'message' => '恭喜你，登录成功！'
            ]);
        }

        $this->ajaxReturn([
            'state' => '1',
            'message' => implode('',array_flatten($model->errors))
        ]);
    }

    # 退出登录
    public function actionLogout()
    {
        Yii::$app->admin->logout();

        return $this->redirect(Url::toRoute('admin/login'));
    }

    # 设置密码 脚本测试
    public function actionSetPass()
    {
        $password = Yii::$app->request->get('pass');
        if (empty($password)) throw new \Exception("密码不能为空");
        $model = new AdminModel();
        $model->setPassword($password);
        echo $model->password_hash;
    }
        
}